package com.chandra.pos.web.context;

import com.chandra.pos.config.database.DatabaseConfigProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.StringUtils;

/**
 * what is an ApplicationContextInitializer. It is essentially code that gets executed before the Spring application context gets completely created.
 * A good use case for using an ApplicationContextInitializer would be to set a Spring environment profile programmatically
 * Created by Admin on 3/19/15.
 */
public class POSApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private static final String SPRING_PROFILES_ACTIVE_PROPERTY = "spring.profiles.active";

    private static final String PROFILE_HSQL = "hsql";

    private final static String[] DEFAULT_ACTIVE_PROFILES = {DatabaseConfigProfile.POSTGRESQL};

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        String springProfilesActive = System.getProperty(SPRING_PROFILES_ACTIVE_PROPERTY);

        if (StringUtils.hasText(springProfilesActive)) {
            logger.info("Using set spring profiles.  profiles='{}'", springProfilesActive);
        } else {
            applicationContext.getEnvironment().setActiveProfiles(DEFAULT_ACTIVE_PROFILES);

            logger.info("Setting default spring profiles.  profiles='{}'", DEFAULT_ACTIVE_PROFILES);
        }
    }

}
